package com.volcreate.inn.controller.admin;


import com.volcreate.inn.po.Type;
import com.volcreate.inn.service.impl.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/admin")
public class ATypeController {


    private static final String EDIT = "admin/category-type-edit";
    private static final String LIST = "admin/category-type";
    private static final String REDIRECT_LIST = "redirect:/admin/type";

    private final TypeService typeService;

    public ATypeController(TypeService typeService) {
        this.typeService = typeService;
    }


    @GetMapping("/type")
    public String paraList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                           Model model) {
        model.addAttribute("page", typeService.listByGmtModifiedDesc(page, 2));
        return LIST;
    }


    @GetMapping("/type/edit")
    public String edit(Model model) {
        model.addAttribute("type", new Type());
        return EDIT;
    }


    // 通过category-type发起的Get请求
    @GetMapping("/type/{id}/edit")
    public String modify(@PathVariable Long id, Model model) {
        // type用于传递默认表单属性,和校验用的一样
        model.addAttribute("type", typeService.getById(id));
        return EDIT;
    }


    @PostMapping("/type")
    public String psot(Type type, BindingResult result, RedirectAttributes attributes) {

        // 存在的，名字为空的，修改id号的操作都不允许。
        String name = type.getName().trim();
        if (name == null || "".equals(name)) {
            result.rejectValue("name", "typeIsEmpty", "类型不能为空");
        }
        // 判断类型是否存在
        Type typeByName = typeService.getByName(name);
        if (typeByName != null) {
            result.rejectValue("name", "typeExist", "类型存在");
        }

        // 不能重定向，否则就没有值，将输出的错误带回
        if (result.hasErrors()) {
            return EDIT;
        }

        boolean t;
        if (type.getId() == null) {
            t = typeService.save(type);
        } else {
            t = typeService.updateById(type);
        }
        if (t) {
            attributes.addFlashAttribute("message", "操作成功");
        } else {
            attributes.addFlashAttribute("message", "操作失败");
        }
        return REDIRECT_LIST;
    }

    @GetMapping("/type/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {
        typeService.removeById(id);
        attributes.addFlashAttribute("message", "删除成功");
        return REDIRECT_LIST;
    }

}